<template>
    <div>
        <div v-if="handle!='view'" class="row">
            <a href="javascript:;" @click="handleResetSelect">重新选择商品</a>
        </div>
        <a-card style="width: 300px">
            <img
                slot="cover"
                :src="detailData.goodsPictures && detailData.goodsPictures.length>0 && detailData.goodsPictures[0] || ''"
                />
            <a-card-meta :title="detailData.goodsName">
                <!-- <div slot="description">
                    &yen;{{detailData.salePrice | formatPrice}}
                </div> -->
            </a-card-meta>
        </a-card>
        <SeckillInventorySettings :handle="handle" :tableData="tableData" :enableMspage="enableMspage" @change="handleSeckillInventorySettings"></SeckillInventorySettings>
        <div class="row flex flex_end">
            <a-space>
                <a-button v-if="handle!='view'" type="primary" @click="handleSave" :disabled="!isCanSubmit" :loading="loading">保存</a-button>
                <a-button @click="handleCancel">取消</a-button>
            </a-space>
        </div>
        <ChooseGoods :visible="chooseGoodsVisible" @cancel="chooseGoodsVisible=false" @submit="handleChooseGoodsSubmit"></ChooseGoods>
    </div>
</template>

<script>
import SeckillInventorySettings from './../components/SeckillInventorySettings';
import ChooseGoods from './../components/ChooseGoods';

export default {
    components:{
        SeckillInventorySettings,
        ChooseGoods
    },
    computed:{
        handle() {
            return this.$route.query.handle || '';
        },
        enableMspage(){
            return this.$route.query.enableMspage || '';
        },
    },
    data(){
        return {
            activityId: '',
            seckillGoodsId: '',
            oldSeckillGoodsId: '',
            productId:'',
            detailData:{}, 
            chooseGoodsVisible:false,           
            tableData:[],
            callbackTableData:[],
            isCanSubmit:false,
            loading:false,
        }
    },
    filters:{
        formatPrice(val){
            if(!val)return '0.00';
            return (val/100).toFixed(2);
        }
    },
    created(){
        console.log(this.enableMspage)
        this.activityId=this.$route.query.activityId || '';
        this.seckillGoodsId=this.$route.query.productId || '';
        this.getProductDetail(this.seckillGoodsId);
        
    },
    methods:{
        //重新选择商品
        handleResetSelect(){
            this.chooseGoodsVisible=true;
        },
        handleChooseGoodsSubmit(id){
            console.log(id)
            this.oldSeckillGoodsId = this.seckillGoodsId
            this.chooseGoodsVisible=false;
            this.seckillGoodsId=id;
            this.getProductDetail(id, 'reset');
        },
        // 获取商品信息
        async getProductDetail(id, type){
            let res=await this.$get('/goods/query',{
                id
            });
            if(res && res.returnCode=='1000'){
                let dataInfo=res.dataInfo || {};
                dataInfo.goodsPictures=dataInfo.goodsPictures.split(',');
                this.detailData=dataInfo;
                if(this.handle == 'add') {
                    this.addGoods(this.activityId, this.seckillGoodsId, this.detailData.goodsBarCodeId, this.detailData.goodsCreateType)
                } else if(type == 'reset') {
                    this.deleteCurrentGood()
                } else {
                    this.getGoodsSpecList(this.activityId, this.seckillGoodsId, this.detailData.goodsBarCodeId, this.detailData.goodsCreateType)
                }
            }
        },
        // 删除商品
        deleteCurrentGood() {
            this.$post('/seckill/goods/delete',
                [ { activityId: this.activityId, goodsId: this.oldSeckillGoodsId } ],
                { baseURL: `${location.origin}/goldenhome/seckill/admin` }).then((res) => {
                if (res && res.returnCode == 1000) {
                    this.addGoods(this.activityId, this.seckillGoodsId, this.detailData.goodsBarCodeId, this.detailData.goodsCreateType)
                } else {
                    this.$message.error('请重新选择商品！');
                }
            });
        },
        // 添加秒杀商品
        async addGoods(activityId, seckillGoodsId, goodsBarCodeId, goodsCreateType){
            let list = [{
                goodId: seckillGoodsId,
                goodsBarCodeId: goodsBarCodeId,
                goodsCreateType: goodsCreateType
            }]
            let res=await this.$post(
                '/seckill/goods/add',
                {
                    activityId: activityId,
                    list: list
                },
                { baseURL: `${location.origin}/goldenhome/seckill/admin` }
            );
            if(res && res.returnCode=='1000'){
                this.getGoodsSpecList(activityId, seckillGoodsId, goodsBarCodeId, goodsCreateType)
            }
        },
        // 获取商品规格信息
        async getGoodsSpecList(activityId, seckillGoodsId, goodsBarCodeId, goodsCreateType){
            let res=await this.$get(
                '/seckill/goodsnorms/list',
                {
                    activityId: activityId,
                    seckillGoodsId: seckillGoodsId,
                    goodsBarCodeId: goodsBarCodeId,
                    goodsCreateType: goodsCreateType
                },
                { baseURL: `${location.origin}/goldenhome/seckill/admin` }
            );
            if(res && res.returnCode=='1000'){
                let dataInfo=res.dataInfo || {};
                this.tableData=dataInfo;
                let _this = this
                for(let i = 0; i<_this.tableData.length; i++){
                    _this.tableData[i].enableSeckill == 1 ? _this.tableData[i].enableSeckill = true : _this.tableData[i].enableSeckill = false
                    _this.tableData[i].salePrice = Number((Number(_this.tableData[i].salePrice)/100).toFixed(2))
                    _this.tableData[i].seckillPrice = _this.tableData[i].seckillPrice ? Number((Number(_this.tableData[i].seckillPrice)/100).toFixed(2)) : 0.01
                    _this.tableData[i].seckillStock = _this.tableData[i].seckillStock || 1
                    if(_this.tableData[i].modelIds == '') { // 统一规格
                        _this.tableData[i].normName = '统一规格'
                    } else { // 多规格
                        let ids = _this.tableData[i].modelIds.split(',')
                        let nameArr = []
                        for(let j = 0; j < ids.length; j++){
                            let name = await _this.getModelNormName(ids[j])
                            nameArr.push(name)
                        }
                        _this.tableData[i].normName = nameArr.join(',')
                    }
                }
            }
        },
        // 获取商品所有规格名称
        async getModelNormName(id) {
            let res = await this.$get('/goods/modelnorm/id', {
                id
            },false,true)
            if(res && res.returnCode=='1000'){
                return res.dataInfo.normName || ''
            }
        },
        handleSeckillInventorySettings(data){
            console.log(data);
            if(data){
                this.tableData = data
            }
            this.callbackTableData=data;
            this.isCanSubmit=!!this.callbackTableData;
        },
        handleCancel(){
            this.$router.push({
                name:'MarketingSeckillPagesCommodityManage',
                query:{
                    activityId:this.activityId,
                    enableMspage: this.enableMspage
                }
            })
        },
        handleSave(){
            this.loading=true;
            let params = [], _this = this
            this.tableData.forEach(item => {
                let flag = {
                    id: item.id,
                    seckillStock: item.seckillStock,
                    seckillPrice: Math.round(item.seckillPrice * 10 * 10),
                    enableSeckill: item.enableSeckill ? 1:0,
                    activityId: _this.activityId
                }
                params.push(flag)
            })
            this.$post(
                '/seckill/goodsnorms/update',
                params,
                { baseURL: `${location.origin}/goldenhome/seckill/admin` }
            ).then(res => {
                if(res && res.returnCode=='1000') {
                    this.loading=false;
                    this.$message.success('秒杀库存设置成功！');
                    this.handleCancel()
                } else {
                    this.loading=false;
                    this.$message.error('秒杀库存设置失败！');
                }
            }).catch(err => {
                this.loading=false;
            })
        }
    }
}
</script>

<style lang="less" scoped>
.row{
    margin-top:10px;
    margin-bottom:10px;
}
.flex{
    display: flex;
    align-items: center;
    justify-content: center;
}
.flex_end{
    justify-content: flex-end;
}
</style>